package com.qidi.socket.service;


import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("tcpServerHandler")
@Scope("prototype")
public class TcpServerHandler extends SimpleChannelInboundHandler<Object>{
    
    private static final Logger logger = Logger.getLogger(TcpServerHandler.class);
    
 

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg)throws Exception {
    	
    	ctx.channel().writeAndFlush("w");
    	
    	
    	String body = new String(msg.toString().getBytes("utf-8"), "UTF-8");

		logger.info("接受到信息："+body);
    }

    /**
     * channel被激活时调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
	logger.debug(ctx.channel().remoteAddress() + "   ----Acrive");
	try {
	    ctx.channel().writeAndFlush("1111111111");
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
			if (evt instanceof IdleStateEvent) {
				IdleStateEvent event = (IdleStateEvent) evt;
				if (event.state().equals(IdleState.READER_IDLE)) { //读取
						logger.debug(ctx.channel().remoteAddress().toString() + "READER_IDLE");
					    logger.debug("------长期未收到服务器反馈数据------");
					    ctx.writeAndFlush("请求客户端重新登录");
					     //根据具体的情况 在这里也可以重新连接
					    //ctx.close();

				} else if (event.state().equals(IdleState.WRITER_IDLE)) { //写超时
						logger.debug(ctx.channel().remoteAddress().toString()+ "WRITER_IDLE");
						// 超时关闭channel
					logger.debug("------长期未向服务器发送数据 发送心跳------");
					logger.debug("------发送心跳包------" + "[LinkTest]\r\n");
					ctx.writeAndFlush("[LinkTest]");
					//	ctx.close();
				} else if (event.state().equals(IdleState.ALL_IDLE)) { //发送心跳
						// 发送心跳
						ctx.channel().writeAndFlush("w");
				}


			}else {

				super.userEventTriggered(ctx, evt);
			}

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
			logger.debug("Unexpected exception from downstream." + cause);
			cause.printStackTrace();
			ctx.close().addListener(ChannelFutureListener.CLOSE);
    }
}
